import { create } from 'zustand'
import { devtools } from 'zustand/middleware'

export interface KafkaMessage {
  topic: string
  partition: number
  offset: number
  timestamp?: number
  key?: string
  value: any
  headers: Record<string, any>
}

export interface TopicInfo {
  name: string
  partitions: number
  partition_info: Array<{
    partition: number
    leader: number
    replicas: number[]
    isr: number[]
  }>
}

interface KafkaState {
  // 连接状态
  isConnected: boolean
  connectionStatus: string
  
  // Topic相关
  topics: string[]
  selectedTopic: string | null
  topicInfo: TopicInfo | null
  
  // 消息相关
  messages: KafkaMessage[]
  isLoading: boolean
  
  // WebSocket相关
  wsConnected: boolean
  
  // Actions
  setConnectionStatus: (status: string, connected: boolean) => void
  setTopics: (topics: string[]) => void
  setSelectedTopic: (topic: string | null) => void
  setTopicInfo: (info: TopicInfo | null) => void
  setMessages: (messages: KafkaMessage[]) => void
  addMessage: (message: KafkaMessage) => void
  setLoading: (loading: boolean) => void
  setWsConnected: (connected: boolean) => void
  clearMessages: () => void
}

export const useKafkaStore = create<KafkaState>()(
  devtools(
    (set, get) => ({
      // Initial state
      isConnected: false,
      connectionStatus: '未连接',
      topics: [],
      selectedTopic: null,
      topicInfo: null,
      messages: [],
      isLoading: false,
      wsConnected: false,
      
      // Actions
      setConnectionStatus: (status, connected) =>
        set({ connectionStatus: status, isConnected: connected }),
      
      setTopics: (topics) => set({ topics }),
      
      setSelectedTopic: (topic) => set({ selectedTopic: topic }),
      
      setTopicInfo: (info) => set({ topicInfo: info }),
      
      setMessages: (messages) => set({ messages }),
      
      addMessage: (message) =>
        set((state) => {
          // 确保消息有唯一标识，避免重复
          const messageKey = `${message.topic}-${message.partition}-${message.offset}`;
          const existingIndex = state.messages.findIndex(
            m => `${m.topic}-${m.partition}-${m.offset}` === messageKey
          );

          // 如果消息已存在，不重复添加
          if (existingIndex !== -1) {
            return state;
          }

          // 添加新消息到开头，保持最新1000条
          const newMessages = [message, ...state.messages].slice(0, 1000);

          // 强制触发重新渲染
          return {
            messages: newMessages
          };
        }),
      
      setLoading: (loading) => set({ isLoading: loading }),
      
      setWsConnected: (connected) => set({ wsConnected: connected }),
      
      clearMessages: () => set({ messages: [] }),
    }),
    {
      name: 'kafka-store',
    }
  )
)
